package edu.toronto.whimper;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

import com.androidplot.Plot;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;

import edu.toronto.whimper.DataProcessor.DBAdapter;
import edu.toronto.whimper.DataProcessor.DBManager;
import edu.toronto.whimper.GeneralObjects.NoiseSample;
import edu.toronto.whimper.GraphsObjects.*;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

public class NoiseExposure extends Activity {
	
	private XYPlot myXYPlot;
	private SampleDynamicSeries seriePlot;
	private MyPlotUpdater plotUpdater;
	private ArrayList <Number> xData = new ArrayList<Number>();
	private ArrayList <Number> yData = new ArrayList<Number>();;
	private DBAdapter db;
	private ArrayList<NoiseSample> allSamples;
	
	private Date datePlot; // = Main.getDate();
	private Button mPickDate;
	private TextView mDateDisplay;
    private int mYear;
    private int mMonth;
    private int mDay;
    
    static final int DATE_DIALOG_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.noiseexposure);  
        //Toast.makeText(this, "on Create", Toast.LENGTH_SHORT).show();        
        //Date section
        mDateDisplay = (TextView) findViewById(R.id.text);
        mPickDate = (Button) findViewById(R.id.pickDate);
        
        // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date
        updateDisplay();        
        //Graph
        //showGraph();
        
   }
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        return null;
    }
    // updates the date we display in the TextView
    private void updateDisplay()
    {
    	mDateDisplay.setText(
                new StringBuilder()
                        .append("Daily Noise Exposure Graph for ")
                        .append(mMonth + 1).append("/")
                        .append(mDay).append("/")
                        .append(mYear).append(" "));
    	int nMonth = mMonth+1;
        String strDate = mYear + "/" + nMonth + "/" + mDay;
        datePlot = Utils.getDateTimeFromStr(strDate, new SimpleDateFormat("yyyy/MM/dd"));
        showGraph();
               
    }
    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    
                    updateDisplay();
                }
            };
            
    @SuppressWarnings("deprecation")
	private void showGraph()
    {    	
    		getDataToPlot();
     		
	        	// get handles to our View defined in layout.xml:
	            myXYPlot = (XYPlot) findViewById(R.id.noiseExposure);
	     
	            plotUpdater = new MyPlotUpdater(myXYPlot);
	     
	            // only display whole numbers in domain labels
	            myXYPlot.getGraphWidget().setDomainValueFormat(new DecimalFormat("0"));
	     
	            // getInstance and position datasets:
	            NoiseDataSource data = new NoiseDataSource(xData,yData);
	            
	            if(seriePlot == null)
	            {
	                // see how to change the date !!!!!! on the bottom of the map
	            	seriePlot = new SampleDynamicSeries(data, 0, datePlot.toString(),getApplicationContext());
	            	myXYPlot.addSeries(seriePlot, new LineAndPointFormatter(
	    	                												Color.rgb(0, 200, 0),                   // line color
	    	                												Color.rgb(0, 100, 0)));                  // point color);
	            	myXYPlot.setDomainLabel("Hours");
	    	        myXYPlot.setRangeLabel("Db");
	            	
	                //myXYPlot.setGridPadding(5, 0, 5, 0);
	         
	                // hook up the plotUpdater to the data model:
	                data.addObserver(plotUpdater);
	         
	                //myXYPlot.setDomainStepMode(XYStepMode.SUBDIVIDE);
	                //myXYPlot.setDomainStepValue(seriePlot.size());
	         
	                // freeze the range boundaries:
	                myXYPlot.setRangeBoundaries(30, 120, BoundaryMode.FIXED);
	                myXYPlot.setTicksPerRangeLabel(3);
	                
	                // X      
	                myXYPlot.setDomainBoundaries(0, 24, BoundaryMode.FIXED);
	                myXYPlot.setTicksPerDomainLabel(3);
	                
	                myXYPlot.disableAllMarkup();
	                               
	                // kick off the data generating thread:
	                new Thread(data).start();
	                
	                
	            }
	            else
	            {
	            	seriePlot.setDataSource(data);
	            } 
	            if(xData.size()== 0 && yData.size()==0)
            	{
            		Toast.makeText(this, "There are no samples for this Date", Toast.LENGTH_SHORT).show();  
            	}
        	
    }
    
    private void getDataToPlot()
    {
    	xData.clear();
    	yData.clear();
    	
    	 db = new DBAdapter(this.getApplicationContext());     	
    	 allSamples = DBManager.getAllNoiseSamples(db);    	 
    	 int count = allSamples.size();
    	       
         if( count > 0)
         {
 	    	for (NoiseSample sample : allSamples) 
 	    	{
 	    		String dateSt = sample.getDate();	
 	    		
 	    		//Toast.makeText( getApplicationContext(), dateSt, Toast.LENGTH_SHORT).show();
 	    		
 	    		Date date = Utils.getDateTimeFromStr(dateSt,new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"));
 	    		
 	    		int numDate = date.getDate();
 	    		    		
 	    		if(numDate == datePlot.getDate())
 	    		{
 	    			int hour = date.getHours();
 	    			int minute = date.getMinutes();
 	    			double dbls = sample.getNoise();
 	    			
 	    			//Toast.makeText( getApplicationContext(), dateSt+"\n"+hour+" "+minute, Toast.LENGTH_SHORT).show();
 	    			
 	    			try
 	    			{
 	    				xData.add(((float)hour+ ((float)minute)/60));
 	 	    			yData.add((Number)dbls);
						
					} catch (Exception e)
					{
						e.printStackTrace();
					    Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
					}
 	    		}    		    	  
 	    	}
         }
         else 
         {
         	Toast.makeText( getApplicationContext(), "There aren't noise samples to be ploted in the graph ", Toast.LENGTH_LONG).show();
         }    	
    }
       
    private class MyPlotUpdater implements Observer {
        Plot plot;
        public MyPlotUpdater(Plot plot) {
            this.plot = plot;
        }
        public void update(Observable o, Object arg) {
            try {
                plot.postRedraw();
            } catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }
}
